package com.yijinsuo.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.yijinsuo.R;
import com.yijinsuo.base.BaseActivity;
import com.yijinsuo.entity.Pagess;
import com.yijinsuo.http.HttpCallBack;
import com.yijinsuo.http.HttpUtils;
import com.yijinsuo.mian.Config;
import com.yijinsuo.pullrefreshlistview.XListView;
import com.yijinsuo.response.UserBorrowInfoRes;
import com.yijinsuo.response.UserBorrowListRes;
import com.yijinsuo.view.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 个人中心,我的投资
 */
public class MyInvestmentActivity extends BaseActivity implements XListView.IXListViewListener {

    @Bind(R.id.titlebar)
    TitleBar titlebar;
    @Bind(R.id.tv_tab_1)
    TextView tvTab1;
    @Bind(R.id.tv_tab_2)
    TextView tvTab2;
    @Bind(R.id.tv_tab_3)
    TextView tvTab3;
    @Bind(R.id.lly_tab)
    LinearLayout llyTab;
    @Bind(R.id.listview_tab1)
    XListView listviewTab1;
    @Bind(R.id.tv_repossessedCapital)
    TextView tvRepossessedCapital;
    @Bind(R.id.tv_tenderInterest)
    TextView tvTenderInterest;
    @Bind(R.id.tv_totalTenderInterest)
    TextView tvTotalTenderInterest;

    //
    private int pageNum = 1;
    private int numPerPage = 10;
    private boolean falg=true;
    private String type = "sucTenderIng";   //默认首款
    private List<Pagess> pages = new ArrayList<Pagess>();
    private TabAdapter tabAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_investment);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {

        titlebar.setTitleBar(R.drawable.back_selector, "我的投资", 0);
        titlebar.setTitleBarRightText("交易记录");
//        titlebar.setTitleBarBackgroundColor(getResources().getColor(R.color.tou_ming));
    }

    @Override
    protected void initView() {

        getuserBorrowInfo();

        getUserBorrowList(pageNum, numPerPage);
    }

    @Override
    protected void setData() {

        tabAdapter = new TabAdapter(MyInvestmentActivity.this, pages);
        listviewTab1.setPullLoadEnable(true);
        listviewTab1.setXListViewListener(this);
        listviewTab1.setAdapter(tabAdapter);

        //
        listviewTab1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Pagess info= (Pagess) tabAdapter.getItem(position-1);
                if(null!=info){
                    Intent intent=new Intent(MyInvestmentActivity.this,TouZiDetailsActivity.class);
                    intent.putExtra("mInvestmentInfo",info);
                    startActivity(intent);
//                    finish();
                }
            }
        });

    }


    @OnClick({R.id.titlebar_iv_back, R.id.tv_tab_1, R.id.tv_tab_2, R.id.tv_tab_3, R.id.titlebar_right_text})

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {


            case R.id.tv_tab_1:
                type = "sucTenderIng";
                pageNum=1;
                pages.clear();
                falg=true;
                getUserBorrowList(pageNum, numPerPage);
                //
                ResetTextColor();
                listviewTab1.setVisibility(View.VISIBLE);
                llyTab.setBackgroundResource(R.mipmap.tab_1);
                tvTab1.setTextColor(getResources().getColor(R.color.white));

                break;


            case R.id.tv_tab_2:
                type = "inTender";
                pageNum=1;
                pages.clear();
                falg=true;
                getUserBorrowList(pageNum, numPerPage);
                //
                ResetTextColor();
                llyTab.setBackgroundResource(R.mipmap.tab_2);
                tvTab2.setTextColor(getResources().getColor(R.color.white));

                break;

            case R.id.tv_tab_3:
                type = "sucTender";
                pageNum=1;
                falg=true;
                pages.clear();
                getUserBorrowList(pageNum, numPerPage);
                //
                ResetTextColor();
                tvTab3.setTextColor(getResources().getColor(R.color.white));
                llyTab.setBackgroundResource(R.mipmap.tab_3);

                break;

            case R.id.titlebar_iv_back:

                finish();

                break;

            case R.id.titlebar_right_text:    //交易记录
                Intent intent1 = new Intent(MyInvestmentActivity.this, TradingRecordActivity.class);
                startActivity(intent1);

                break;

            default:

        }


    }

    /**
     * 重置tab颜色字体
     */

    public void ResetTextColor() {
        tvTab1.setTextColor(getResources().getColor(R.color.black_6));
        tvTab2.setTextColor(getResources().getColor(R.color.black_6));
        tvTab3.setTextColor(getResources().getColor(R.color.black_6));

    }


    class TabAdapter extends BaseAdapter {
        private Context cotext;
        private List<Pagess> infos;
        private LayoutInflater inflater;

        public TabAdapter(Context cotext, List<Pagess> infos) {
            this.cotext = cotext;
            this.infos = infos;
            inflater = LayoutInflater.from(cotext);
        }

        public void UpdateAdapter(List<Pagess> infos) {
            this.infos = infos;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return infos.size();
        }

        @Override
        public Object getItem(int position) {
            return infos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (viewHolder == null) {
                viewHolder = new ViewHolder();
                convertView = inflater.inflate(R.layout.investment_tab_one_item, null);
                viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.tv_stayingInterest= (TextView) convertView.findViewById(R.id.tv_stayingInterest);
                viewHolder.tv_interestPaid= (TextView) convertView.findViewById(R.id.tv_interestPaid);
                viewHolder.tv_effectiveAmount= (TextView) convertView.findViewById(R.id.tv_effectiveAmount);
                viewHolder.tv_endTime= (TextView) convertView.findViewById(R.id.tv_endTime);
                if(type.equals("inTender")){
                    viewHolder.tv_stayingInterest.setVisibility(View.GONE);
                }

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            Pagess info = infos.get(position);
            viewHolder.tv_name.setText(info.getBorrowTitle());


            viewHolder.tv_stayingInterest.setText("预期收益: "+info.getInterestAmount()+"元");
            viewHolder.tv_interestPaid.setText("收益率: "+info.getAnnualInterestRate()+"%");
            viewHolder.tv_effectiveAmount.setText("金额:  "+info.getEffectiveAmount()+"元");
            String endtime="";
            if(!info.getEndTime().equals("")){
                 endtime=info.getEndTime().substring(0,info.getEndTime().lastIndexOf(" "));
            }
            viewHolder.tv_endTime.setText("到期日:  "+endtime);

            return convertView;
        }


    }

    public final class ViewHolder {

        TextView tv_name;
        TextView tv_stayingInterest;
        TextView tv_interestPaid;
        TextView tv_effectiveAmount;
        TextView tv_endTime;


    }


    /**
     * 获取我资产
     */
    private void getuserBorrowInfo() {

        HttpParams params = new HttpParams();
        HttpUtils.post(Config.USERBORROWINFO, params, new HttpCallBack(MyInvestmentActivity.this, "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (null != result) {
                    try {
                        UserBorrowInfoRes res = new UserBorrowInfoRes(new JSONObject(result.toString()));
                        tvRepossessedCapital.setText("￥ " + res.getRepossessedCapital());
                        tvTenderInterest.setText("￥ " + res.getTenderInterest());
                        tvTotalTenderInterest.setText("￥ " + res.getTotalTenderInterest());

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(String code, String message) {

                Toast.makeText(MyInvestmentActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onRefresh() {

        pageNum = 1;
        falg = true;

        getUserBorrowList(pageNum, numPerPage);
    }


    @Override
    public void onLoadMore() {
        pageNum++;
        falg = false;
        getUserBorrowList(pageNum, numPerPage);
    }

    /**
     * 获取我的资产列表数据
     *
     * @param pageNum
     * @param numPerPage
     */
    private void getUserBorrowList(int pageNum, int numPerPage) {

        HttpParams params = new HttpParams();
        params.put("type", type);
        params.put("pageNum", pageNum + "");
        params.put("numPerPage", numPerPage + "");
        HttpUtils.post(Config.USERBORROWLIST, params, new HttpCallBack(MyInvestmentActivity.this, "加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

                if (null != result) {
                    try {
                        UserBorrowListRes res = new UserBorrowListRes(new JSONObject(result.toString()));
                        if(falg==true){
                            if(res.getPage().size()>0){
                                pages=res.getPage();
                            }else {
                                pages.clear();
                                Toast.makeText(MyInvestmentActivity.this, "查无数据", Toast.LENGTH_SHORT).show();
                            }

                        }else{
                            if(!res.getCurrentPage().equals(res.getTotalPage())){
                                pages.addAll(res.getPage());
                            }else{
                                Toast.makeText(MyInvestmentActivity.this, "无更多加载数据", Toast.LENGTH_SHORT).show();
                            }
                        }


                        //
                        tabAdapter.UpdateAdapter(pages);
                        //释放
                        onLoad();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String code, String message) {
                //释放
                onLoad();
                Toast.makeText(MyInvestmentActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        });


    }

    private void onLoad() {
        listviewTab1.stopRefresh();
        listviewTab1.stopLoadMore();
        listviewTab1.setRefreshTime("刚刚");
    }

}
